package ru.payment.wm.impl;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;

import ru.payment.wm.Signer;
import ru.payment.wm.WebMoneyException;

/**
 *
 * User: sergey
 * Date: 10.04.2009
 * Time: 15:30:23
 *
 * На эти интерфейсы необходимо открывать доступ
 * Х2, X5, X6, X7, X8, X9, X13, X14, X15
 */
public class LightWebMoneyService extends AbstractWebMoneyService {

  private String trustStorePath;
  private String keyStorePath;
  private String trustStorePassword;
  private String keyStorePassword;
  private boolean keyStoreInited = false;

  public LightWebMoneyService() {
    setUrlProvider(new LightUrlProvider());
  }

  public LightWebMoneyService(String trustPath, String trustPwd, String keyPath, String keyPwd) {
    this();
    setTrustStorePath(trustPath);
    setTrustStorePassword(trustPwd);
    setKeyStorePath(keyPath);
    setKeyStorePassword(keyPwd);
  }

  public String getTrustStorePath() {
    return trustStorePath;
  }

  public void setTrustStorePath(String trustStorePath) {
    this.trustStorePath = trustStorePath;
  }

  public String getKeyStorePath() {
    return keyStorePath;
  }

  public void setKeyStorePath(String keyStorePath) {
    this.keyStorePath = keyStorePath;
  }

  public String getTrustStorePassword() {
    return trustStorePassword;
  }

  public void setTrustStorePassword(String trustStorePassword) {
    this.trustStorePassword = trustStorePassword;
  }

  public String getKeyStorePassword() {
    return keyStorePassword;
  }

  public void setKeyStorePassword(String keystorePassword) {
    this.keyStorePassword = keystorePassword;
  }

  protected boolean isSignerEnabled() {
    return false;
  }

  public Signer getSigner() {
    return null;
  }

  // ---------------------------------------------------------------------------

  protected void onBeforeRequest() throws WebMoneyException {
    if (!keyStoreInited) {
      initSecurity();
    }
  }

  protected synchronized void initSecurity() throws AuthorizationException {

    if (keyStoreInited) {
      return;
    }

    try {

      // загружаем ключ с корневым сертификатом WebMoney
      KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
      FileInputStream instream = new FileInputStream(new File(trustStorePath));
      try {
        trustStore.load(instream, trustStorePassword.toCharArray());
      } finally {
        instream.close();
      }

      // Загружаем ключ, импортированный из браузера
      KeyStore keyStore  = KeyStore.getInstance("PKCS12");
      instream = new FileInputStream(new File(keyStorePath));
      try {
        keyStore.load(instream, keyStorePassword.toCharArray());
      } finally {
        instream.close();
      }

      // активируем поддержку SSL
      SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, keyStorePassword, trustStore);

      // Try to prevent "SSLException hostname in certificate didn't match" from happening.
      try {
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      } catch (Throwable deprecatedMethod) {} // setHostnameVerifier is a deprecated method, might be unavailable in the future.
      HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      Scheme sch = new Scheme("https", 443, socketFactory);

      getHttpClient().getConnectionManager().getSchemeRegistry().register(sch);

    } catch (Exception e) {
      throw new AuthorizationException(e);
    }

    keyStoreInited = true;
  }

}
